package pl.com.hme.kody.pocztowe.service;

import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpHead;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;

import android.util.Log;

public class HttpQueryMaker {

    private static String TAG = "HttpQueryMaker";

    private static URI mUriAddress = URI.create("http://www.poczta-polska.pl/kody/index.php");

    private static List<NameValuePair> getNameValuePairsForCityAndStreet(String city, String street) {
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
        nameValuePairs.add(new BasicNameValuePair("miejsc", city));
        nameValuePairs.add(new BasicNameValuePair("page", "miejsc"));
        nameValuePairs.add(new BasicNameValuePair("ulica", street));

        return nameValuePairs;
    }

    public static HttpResponse getDummyIndexPage(HttpClient httpClient) throws ClientProtocolException, IOException {

        HttpHead httpHead = new HttpHead(mUriAddress);

        HttpResponse response = httpClient.execute(httpHead);

        return response;
    }

    private static InputStream getInputStreamFromHttp(URI addressUri, List<NameValuePair> postNameValuePairs, HttpClient httpClient) throws HttpException, ClientProtocolException, IOException {

        HttpPost httpPost = new HttpPost(addressUri);

        httpPost.setEntity(new UrlEncodedFormEntity(postNameValuePairs));

        HttpResponse response = httpClient.execute(httpPost);

        Log.v(TAG, "Status line " + response.getStatusLine().toString());

        HttpEntity entity = response.getEntity();

        if (entity != null) {
            return entity.getContent();
        } else {
            throw new HttpException("Null Http response body");
        }

    }

    public static InputStream getCodeFromCityAndStreet(String city, String street, HttpClient httpClient) throws HttpException, ClientProtocolException, IOException {
        return getInputStreamFromHttp(mUriAddress, getNameValuePairsForCityAndStreet(city, street), httpClient);
    }
}
